#!/usr/bin/env python
"""
调试景点数据和图片显示问题
"""
import os
import sys
import django

# 设置Django环境
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'travel_plan.settings')
django.setup()

from apps.attractions.models import Attraction
from apps.attractions.serializers import AttractionSerializer
from django.test import RequestFactory
from django.contrib.auth.models import User

def debug_attractions():
    print("=" * 60)
    print("景点数据调试")
    print("=" * 60)

    # 1. 检查数据库中的景点数量
    total_count = Attraction.objects.count()
    print(f"\n1. 总景点数: {total_count}")

    # 2. 检查有图片的景点
    with_images = Attraction.objects.filter(
        amap_image_urls__isnull=False
    ).exclude(amap_image_urls=[])
    with_images_count = with_images.count()
    print(f"有图片的景点数: {with_images_count}")

    no_images = total_count - with_images_count
    print(f"没有图片的景点数: {no_images}")

    # 3. 检查前3个景点的详细数据
    print("\n3. 前3个景点的详细数据:")
    for i, attr in enumerate(Attraction.objects.all()[:3], 1):
        print(f"\n景点 {i}: {attr.name}")
        print(f"  POI ID: {attr.amap_poi_id}")
        print(f"  图片数量: {len(attr.amap_image_urls) if attr.amap_image_urls else 0}")
        if attr.amap_image_urls and len(attr.amap_image_urls) > 0:
            print(f"  第一张图片: {attr.amap_image_urls[0][:100]}...")
        else:
            print("  图片: 无"

    # 4. 测试序列化器输出
    print("
4. 测试序列化器输出:")
    try:
        # 创建测试用户（如果需要）
        try:
            user = User.objects.get(username='test')
        except User.DoesNotExist:
            user = User.objects.create_user(username='test', email='test@test.com', password='test123')

        # 创建测试请求
        factory = RequestFactory()
        request = factory.get('/api/attractions/')
        request.user = user

        # 序列化第一个景点
        if Attraction.objects.exists():
            attraction = Attraction.objects.first()
            serializer = AttractionSerializer(attraction, context={'request': request})
            data = serializer.data

            print(f"序列化结果:")
            print(f"  名称: {data.get('name')}")
            print(f"  primary_image: {data.get('primary_image')}")
            print(f"  amap_images: {data.get('amap_images')}")
            print(f"  amap_image_urls长度: {len(data.get('amap_image_urls', []))}")

            if data.get('primary_image'):
                print(f"  primary_image URL: {data.get('primary_image')[:100]}...")
    except Exception as e:
        print(f"序列化测试失败: {str(e)}")

    # 5. 检查各类别统计
    print("
5. 各类别统计:")
    categories = ['cultural', 'natural', 'modern', 'food']
    for cat in categories:
        count = Attraction.objects.filter(category=cat).count()
        with_img = Attraction.objects.filter(category=cat).filter(
            amap_image_urls__isnull=False
        ).exclude(amap_image_urls=[]).count()
        print(f"  {cat}: 总数{count}, 有图片{with_img}")

    print("
6. 建议:")
    if no_images > 0:
        print("  ⚠️  发现没有图片的景点，建议重新运行获取命令")
    if with_images_count == 0:
        print("  ❌ 没有找到任何有图片的景点，检查数据获取过程")
    if total_count == 0:
        print("  ❌ 数据库中没有景点数据，运行获取命令")

    if with_images_count > 0 and total_count > 0:
        percentage = (with_images_count / total_count) * 100
        print(".1f"        if percentage >= 80:
            print("  ✅ 图片数据完整，可以测试前端显示")
        else:
            print("  ⚠️  图片数据不完整，建议重新获取")

if __name__ == '__main__':
    debug_attractions()
